package com.wn.login.user

import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ToastUtils
import com.wn.common.constant.USER_ACTIVITY_SETTING
import com.wn.common.dialog.LogoutTipsDialog
import com.wn.common.dialog.MessageDialog
import com.wn.common.provider.LoginServiceProvider
import com.wn.common.provider.SearchServiceProvider
import com.wn.common.provider.UserServiceProvider
import com.wn.common.utils.FileManager
import com.wn.framework.base.BaseActivity
import com.wn.framework.ext.onClick
import com.wn.framework.utils.ViewUtils.setClipViewCornerRadius
import com.wn.mod_login.R
import com.wn.mod_login.databinding.ActivitySettingBinding
import com.wn.network.utils.CookiesManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2025/8/7 15:38
 * @Description: 设置页面
 */
@AndroidEntryPoint
@Route(path = USER_ACTIVITY_SETTING)
class SettingActivity : BaseActivity<ActivitySettingBinding>() {

  override fun getLayoutRes() = R.layout.activity_setting

  @Inject
  lateinit var cookiesManager: CookiesManager

  // 空值 初始化 -- 缓存路径
  private val allCacheDir = arrayOfNulls<String>(2)

  override fun initView() {
    mBinding.apply {
      setClipViewCornerRadius(tvLogout, ConvertUtils.dp2px(8.0F))
      tvLogout.isVisible = UserServiceProvider.isLogin()

      tvCurrentVersion.text =
        String.format(
          getString(com.wn.framework.R.string.setting_current_version),
          AppUtils.getAppVersionName()
        )
      // 获取文件存储根目录
      val rootDir = FileManager.getAppRootDir()
      // 创建图片换成目录
      val imageDir = FileManager.getImageDirectory(this@SettingActivity).absolutePath

      allCacheDir[0] = rootDir
      allCacheDir[1] = imageDir
    }
    // 在 IO 协程 中计算缓存大小
    lifecycleScope.launch(Dispatchers.IO) {
      withContext(Dispatchers.Main) {
        initCacheSize()
      }
    }
    initListener()
  }

  /**
   * 初始化缓存大小
   */
  private fun initCacheSize() {
    val size = FileManager.getTotalCacheSize(this, *allCacheDir)
    mBinding.tvCache.text = size
  }


  private fun initListener() {
    mBinding.apply {
      // 跳转用户信息页
      clUserInfo.onClick {
        UserInfoActivity.start(this@SettingActivity)
      }
      // 最新版本
      clCurrentVersion.onClick {
        ToastUtils.showShort(com.wn.framework.R.string.setting_newest_version)
      }
      // 跳转到 隐私协议 页
      clPrivacyPolicy.onClick {
        LoginServiceProvider.readPolicy(this@SettingActivity)
      }
      // 清除缓存
      clClearCache.onClick {
        showClearCacheDialog()
      }
      // 跳转到 关于 页面
      clAboutUs.onClick {
        AboutUsActivity.start(this@SettingActivity)
      }
      // 退出
      tvLogout.onClick {
        // 确认时 调用
        LogoutTipsDialog.Builder(this@SettingActivity) {
          showLoading("正在退出...")
          // Observer<Boolean> 接口 只有一个方法 就是 lambda
          LoginServiceProvider.logout(this@SettingActivity, lifecycleOwner) {
            // it -- true 表示  API调用失败
            // 1 清除缓存
            cookiesManager.clearCookies()
            // 2 清除用户信息
            UserServiceProvider.clearUserInfo()
            // 3 清除搜索历史缓存
            SearchServiceProvider.clearSearchHistoryCache()
            // 4 隐藏 退出按钮
            tvLogout.isVisible = false
            // 5 关闭加载框
            dismissLoading()
          }
        }.show()
      }
    }
  }

  private fun showClearCacheDialog() {
    MessageDialog.Builder(this)
      .setTitle(getString(com.wn.framework.R.string.dialog_tips_title))
      .setMessage(getString(com.wn.framework.R.string.setting_clear_cache_tips))
      .setConfirm(getString(com.wn.framework.R.string.default_confirm))
      .setConfirmTxtColor(getColor(com.wn.framework.R.color.color_0165b8))
      .setCancel(getString(com.wn.framework.R.string.default_cancel))
      .setonCancelListener {
        // 取消
        it?.dismiss()
      }
      .setonConfirmListener {
        // 确认
        clearCache()
        it?.dismiss()
      }
      .create()
      .show()
  }

  /**
   * 清理缓存
   * 主要 针对 文件存储根目录 ， 创建图片换成目录
   */
  private fun clearCache() {
    showLoading("正在清理...")
    lifecycleScope.launch(Dispatchers.IO) {
      allCacheDir.forEach {
        it?.apply {
          FileManager.delAllFile(this)
        }
      }
      delay(500)
      // 清理完成后 重新计算缓存大小
      withContext(Dispatchers.Main) {
        initCacheSize()
        dismissLoading()
      }
    }
  }
}